package com.atguigu.eduorder.controller;


import com.atguigu.commonutils.JwtUtils;
import com.atguigu.commonutils.R;
import com.atguigu.commonutils.ordervo.UcenterMemberOrder;
import com.atguigu.eduorder.client.UcenterServiceClient;
import com.atguigu.eduorder.entity.Order;
import com.atguigu.eduorder.service.OrderService;
import com.atguigu.servicebase.exceptionHandler.GuliException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 订单 前端控制器
 * </p>
 *
 * @author testjava
 * @since 2021-02-04
 */
@RestController
@RequestMapping("/eduorder/order")
@CrossOrigin
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private UcenterServiceClient ucenterServiceClient;

    //1生成订单的方法
    @PostMapping("createOrder/{courseId}")
    public R saveOrder(@PathVariable String courseId, HttpServletRequest request){
        String memberId=JwtUtils.getMemberIdByJwtToken(request);//得到用户id
        if(StringUtils.isEmpty(memberId)){
            throw new GuliException(20001,"请先进行登录");
        }
        String orderNo=orderService.createOrders(courseId,memberId);
        return R.ok().data("orderId",orderNo);
    }

    //2根据订单id查询订单信息
    @GetMapping("getOrderInfo/{orderId}")
    public R getOrderInfo(@PathVariable String orderId){
        QueryWrapper<Order> wrapper=new QueryWrapper<>();
        wrapper.eq("order_no",orderId);
        Order order=orderService.getOne(wrapper);
        return R.ok().data("item",order);
    }

    //3测试
    @GetMapping("test")
    public R test(){
        UcenterMemberOrder ucenterMemberOrder=ucenterServiceClient.getUserInfoOrder("1");
        return R.ok().data("success",ucenterMemberOrder);
    }

    //查询订单数据
    @GetMapping("queryOrderInfo/{courseId}/{memberId}")
    public boolean queryOrderInfo(@PathVariable String courseId,@PathVariable String memberId){
        QueryWrapper<Order> wrapper=new QueryWrapper<>();
        wrapper.eq("member_id",memberId);
        wrapper.eq("course_id",courseId);
        wrapper.eq("status",1);
        int count=orderService.count(wrapper);
        if(count>0){
            return true;
        }
        return false;
    }
}

